package com.wmapp.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.io.XMLWriter;
import org.springframework.util.FileCopyUtils;

import com.wmapp.DomainConvertException;
/**
 * Manage pserver storage.
 * Singleton pattern.
 * Its path will be registered by web container as it is starting
 * @author dengl
 *
 */
public class Pserver {
	private static Log log=LogFactory.getLog(Pserver.class);
	
	public static final String MCU_CONTEXT_FILE_NAME="MCUContext.xml";
	
	private String path;//pserver folder real path,injected by web container when it is starting
	private String contextPath;//web context name
	private static Pserver instance;
	
	protected Pserver(){};
	
	public synchronized static Pserver getInstance(){
		if(instance==null)
			instance=new Pserver();
		return instance;
	}
	
	public synchronized String getPath(){
		return path;
	}
	
	public synchronized void setPath(String path){
		this.path=path;
	}
	
	public synchronized String getContextPath() {
		return contextPath;
	}

	public synchronized void setContextPath(String path) {
		this.contextPath = path;
	}

	public Document file2Document(String fileName){
		Document doc=null;
		
		if(path!=null){
			try {
				File xmlfile=new File(SimpleStringUtils.join(path,"/",fileName));
				String xmlStr=new String(FileCopyUtils.copyToByteArray(xmlfile));
				doc=DocumentHelper.parseText(xmlStr);
			} catch (Exception e) {
				log.error(SimpleStringUtils.join(fileName," convert to dom4j document fail.please check xml syntax."), e);
				throw new DomainConvertException(e.getMessage());
			}
		}
		
		return doc;
	}
	
	public void document2File(Document doc,String fileName){
		XMLWriter writer=null;
		try {
			writer = new XMLWriter(new FileWriter(SimpleStringUtils.join(path,"/",fileName)));
			writer.write( doc );
		} catch (IOException e) {
			log.error(SimpleStringUtils.join("dom4j document convert to file ",fileName," fail."), e);
			throw new DomainConvertException(e.getMessage());
		} finally{
			if(writer!=null)
				try {
					writer.close();
				} catch (IOException e2) {
					//ignore..
				}
		}
	}
	
	public static Node getNodeByText(List nodes,String nodeText){
		Node ret=null;
		
		for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
			Node node = (Node) iterator.next();
			if(node.getText().equals(nodeText)){
				ret=node;
				break;
			}
		}
		
		return ret;
	}
}
